<template>
  <div class="product-shipment-wrap">
    <!-- 条件查询区域 -->
    <el-card class="mb16">
      <el-form :model="queryForm" inline :inline-message="true">
        <el-form-item label="发货单号" prop="shipmentId">
          <el-input
              v-model="queryForm.shipmentId"
              placeholder="请输入发货单号"
              clearable
              style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="订单编号" prop="orderId">
          <el-input
              v-model="queryForm.orderId"
              placeholder="请输入订单编号"
              clearable
              style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 180px"
          >
            <el-option label="未发货" value="0" />
            <el-option label="已发货" value="1" />
            <el-option label="已收货" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row justify="space-between" align="middle" class="mb16">
      <el-button type="primary" :icon="Plus" @click="openAdd">新增发货</el-button>
      <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          v-model:current-page="page"
          @current-change="loadData"
          class="pagination"
      />
    </el-row>

    <el-table :data="tableData" stripe v-loading="loading" border>
      <el-table-column prop="shipmentId" label="发货单号" width="200" />
      <el-table-column prop="orderId" label="订单编号" width="200" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusColor(row.status)">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="shipmentTime" label="发货时间" width="200">
        <template #default="{ row }">
          {{ row.shipmentTime ? new Date(row.shipmentTime).toLocaleString() : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="160" fixed="right">
        <template #default="{ row }">
          <el-button
              size="small"
              @click="openEdit(row)"
              v-if="row.status === 0"
          >
            编辑
          </el-button>
          <el-popconfirm title="确定删除?" @confirm="handleDelete(row.shipmentId)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>

          <!-- 只有未发货状态可以执行发货操作 -->
          <el-button
              v-if="row.status === 0"
              size="small"
              type="success"
              @click="doShipment(row)"
          >
            执行发货
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
        v-model="drawer"
        :title="isAdd ? '新增发货' : '编辑发货'"
        direction="rtl"
        size="420"
        destroy-on-close
        @closed="resetForm"
    >
      <el-form
          ref="formRef"
          :model="form"
          label-width="90px"
          :rules="formRules"
      >
        <el-form-item label="发货单号" prop="shipmentId">
          <el-input
              v-model="form.shipmentId"
              placeholder="请输入发货单号"
              :disabled="!isAdd"
          />
        </el-form-item>
        <!-- ProductShipment.vue 中订单编号的表单项修改 -->
        <el-form-item label="订单编号" prop="orderId">
          <el-select
              v-model="form.orderId"
              placeholder="请选择订单编号"
              clearable
              style="width:100%"
          >
            <el-option
                v-for="order in orderOptions"
                :key="order.value"
                :label="order.label"
                :value="order.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">未发货</el-radio>
            <el-radio :label="1">已发货</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发货时间" prop="shipmentTime">
          <el-date-picker
              v-model="form.shipmentTime"
              type="datetime"
              placeholder="选择发货时间"
              style="width:100%"
              :disabled="form.status === 0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ElMessage, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
// 引入订单查询接口（用于获取已付款订单）
import { findSearchOrders } from '../../api/orderApi.js'
import {
  findAllShipment as findAll,
  addShipment as add,
  updateShipment as update,
  deleteShipment as deleteById,
  findShipmentByCondition,getPaidUnshippedOrders , updateShipment
} from '../../api/wms.js'

const defaultForm = () => ({
  shipmentId: '',
  orderId: '',
  status: 0,
  shipmentTime: null  // 新增时默认为空，而非new Date()
})

export default {
  name: 'ProductShipment',
  components: {},
  setup() {
    return { Plus }
  },
  data() {
    return {
      allData: [],
      loading: false,
      tableData: [],
      total: 0,
      page: 1,
      size: 6,
      drawer: false,
      isAdd: true,
      form: defaultForm(),
      formRules: {
        shipmentId: [
          { required: true, message: '请输入发货单号', trigger: 'blur' },
          { max: 50, message: '发货单号长度不能超过50个字符', trigger: 'blur' }
        ],
        orderId: [
          { required: true, message: '请选择订单编号', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        shipmentTime: [
          { required: false, message: '请选择发货时间', trigger: 'change', type: 'date' }
        ]
      },
      statusMap: { 0: '未发货', 1: '已发货' ,2:'已收货'},
      queryForm: {
        shipmentId: '',
        orderId: '',
        status: null
      },
      // 新增：已付款订单下拉数据
      paidOrders: [],orderOptions: [],
      orderLoading: false
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const res = await findShipmentByCondition(this.queryForm)
        this.allData = res?.data?.data || []

        this.total = this.allData.length
        const startIndex = (this.page - 1) * this.size
        const endIndex = startIndex + this.size
        this.tableData = this.allData.slice(startIndex, endIndex)
      } catch (error) {
        ElMessage.error('加载数据失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    // 新增：加载已付款且未发货的订单
    async loadPaidUnshippedOrders() {
      try {
        const res = await getPaidUnshippedOrders();
        // 关键修复：将订单数据映射为{label, value}格式
        this.orderOptions = (res?.data?.data || []).map(order => ({
          label: order.orderId, // 显示的订单编号文本
          value: order.orderId  // 绑定的订单编号值
        }));
      } catch (error) {
        ElMessage.error('加载订单列表失败：' + (error.message || '未知错误'));
      }
    },
    // 新增：获取已付款订单列表（状态为2）
    async getPaidOrders() {
      this.orderLoading = true
      try {
        const res = await findSearchOrders({
          status: 2, // 已付款状态
          pageNum: 1,
          pageSize: 100 // 加载足够多的订单供选择
        })
        // 格式化订单数据为下拉选项格式
        this.paidOrders = (res?.data?.data?.list || []).map(order => ({
          value: order.orderId,
          label: order.orderId
        }))
      } catch (error) {
        ElMessage.error('获取已付款订单失败：' + (error.message || '未知错误'))
      } finally {
        this.orderLoading = false
      }
    },
    statusColor(st) {
      return ['warning', 'success'][st] || 'info'
    },
    // 在打开新增/编辑抽屉时调用，确保下拉数据最新
    openAdd() {
      this.isAdd = true;
      this.form = defaultForm();
      this.drawer = true;
      this.loadPaidUnshippedOrders(); // 打开时加载下拉数据
    },
    openEdit(row) {
      this.isAdd = false;
      this.form = { ...row };
      this.drawer = true;
      this.loadPaidUnshippedOrders(); // 编辑时也加载（可选）
    },
    async handleDelete(id) {
      try {
        await deleteById(id)
        ElMessage.success('删除成功')
        this.loadData()
      } catch (error) {
        ElMessage.error('删除失败：' + (error.message || '未知错误'))
      }
    },
    async submit() {
      const formRef = this.$refs.formRef
      if (!formRef) return

      try {
        await formRef.validate()
        if (this.form.status === 1 && !this.form.shipmentTime) {
          this.form.shipmentTime = new Date()
        }
        // 若为编辑状态，且状态改为“已发货”（1），自动设置当前时间
        if (!this.isAdd && this.form.status === 1) {
          this.form.shipmentTime = new Date();  // 执行发货时填充当前时间
        }

        const api = this.isAdd ? add : update
        await api(this.form)
        ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
        this.drawer = false
        this.loadData()
      } catch (error) {
        if (error.name === 'ValidationError') return
        ElMessage.error((this.isAdd ? '新增' : '修改') + '失败：' + (error.message || '未知错误'))
      }
    },
    resetForm() {
      const formRef = this.$refs.formRef
      if (formRef) formRef.resetFields()
      this.form = defaultForm()
    },
    async doShipment(row) {
      // 正确创建loading实例（关键修复：定义loading变量）
      const loading = ElLoading.service({
        text: '正在执行发货...',
        lock: true // 锁定屏幕防止重复操作
      });

      try {
        // 调用更新接口，设置状态为已发货并更新时间
        await updateShipment({
          shipmentId: row.shipmentId,
          orderId:row.orderId,
          status: 1, // 1表示已发货
          shipmentTime: new Date() // 发货时间设为当前时间
        });
        ElMessage.success('发货成功');
        this.loadData(); // 重新加载数据刷新表格
      } catch (error) {
        ElMessage.error('发货失败：' + (error.message || '未知错误'));
      } finally {
        // 无论成功失败，都关闭加载状态
        loading.close();
      }
    },
    handleQuery() {
      this.page = 1
      this.loadData()
    },
    resetQuery() {
      this.queryForm = {
        shipmentId: '',
        orderId: '',
        status: null
      }
      this.page = 1
      this.loadData()
    }
  }
}
</script>

<style scoped>
.product-shipment-wrap {
  padding: 16px;
  //background: var(--bg-0);
  min-height: 100%;
}
.mb16 {
  margin-bottom: 16px;
}
::v-deep .el-table__cell {
  padding: 12px 0;
}
.pagination {
  text-align: right;
}
</style>